// ignore_for_file: non_constant_identifier_names, invalid_use_of_protected_member
import 'dart:async';
import 'dart:math';

import 'package:bt_dsp_88/model/model_send.dart';
import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:flutter_keyboard_visibility/flutter_keyboard_visibility.dart';
import 'package:flutter_kit_plus/flutter_kit.dart';

import '../../class/dialog/memory_view.dart';
import '../../class/dialog/upload_view.dart';
import '../../model/model_default.dart';
import '../../model/model_extension.dart';
import '../../notify/globalState.dart';
import '../../tool/assets.dart';
import 'class/cross/cross_controller.dart';
import 'class/dialog/noise.dart';
import 'class/dialog/password_input.dart';
import 'class/eq/eq_controller.dart';
import 'class/gain/gain_controller.dart';
import 'class/search/search_device_view.dart';
import 'class/sum/sum_controller.dart';
import 'commont/base_controller.dart';
import 'file_receiver.dart';
import 'log.dart';
import 'main.dart';

class MyHomeController extends StatefulWidget {
  const MyHomeController({super.key});

  @override
  State<MyHomeController> createState() => _MyHomeControllerState();
}

class _MyHomeControllerState extends State<MyHomeController> with WidgetsBindingObserver {
  AppLifecycleState? _appLifecycleState;
  double _keyboardHeight = 0;

  List<List<int>> _upload_list = [];
  int _currentIndex = 0;

  final List<String> _titles = ['SUMMING', 'CROSSOVER', 'GAIN', 'OUTPUT EQ'];
  final List<String> _items = [
    assets.summing,
    assets.cross,
    assets.gain,
    assets.eq,
  ];
  final List<String> _items_select = [
    assets.summing_select,
    assets.cross_select,
    assets.gain_select,
    assets.eq_select,
  ];
  late final List<BaseController> _pages;
  late final LongPressGestureRecognizer _longPressRecognizer;
  StreamSubscription? _conncetSubscription;
  StreamSubscription? _responsesSubscription;

  @override
  void initState() {
    WidgetsBinding.instance.addObserver(this);
    _longPressRecognizer = LongPressGestureRecognizer(duration: const Duration(milliseconds: 6000))
      ..onLongPress = () {
        NoiseView noiseView = NoiseView();
        noiseView.show(context);
        noiseView.onOk = (index) {
          globalState.state = NotifyData(key: 'NOISE', body: index);
        };
      };
    super.initState();
    _pages = [SumController(), CrossController(), GainController(), EqController()];

    globalState.addListener((data) {
      if (data.key == '全部刷新') {
        realodAllPage();
        setState(() {});
      }
    });

    listenBluetooth(context);

    ///主动读取应用外的文件
    // WidgetsBinding.instance.addPostFrameCallback((_) async {
    //   readFile();
    // });

    ///被动监听应用外的文件
    listenFile();
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    setState(() {
      _appLifecycleState = state;
    });

    // 检测应用状态
    if (state == AppLifecycleState.resumed) {
      print("应用进入前台");
    } else if (state == AppLifecycleState.paused) {
      print("应用进入后台");
    } else if (state == AppLifecycleState.inactive) {
      print("应用处于非活动状态");
    } else if (state == AppLifecycleState.detached) {
      print("应用被完全移除");
    }
  }

  @override
  void didChangeMetrics() {
    super.didChangeMetrics();
    final bottomInsets = WidgetsBinding.instance.addPostFrameCallback((_) {
      var bottom = MediaQuery.of(context).viewInsets.bottom;
      _keyboardHeight = bottom;
      print('=========================>>>>>>>>>>>>   ${bottom}');
    });
  }

  ///tab按钮
  List<BottomNavigationBarItem> get _tabItems {
    Widget _icon(String img, Color? color) {
      return Transform.scale(
        scale: 2.0,
        child: Padding(
            padding: const EdgeInsets.only(top: 5, left: 5, right: 5, bottom: 0),
            child: Image.asset(
              img,
              fit: BoxFit.cover,
              color: color,
              height: 20,
            )),
      );
    }

    return List.generate(_items.length, (index) {
      return BottomNavigationBarItem(
        label: '', // 隐藏标签
        icon: _icon(_items[index], lock(index) ? Color_disEnable : null), // 默认状态的图标
        activeIcon: _icon(_items_select[index], lock(index) ? Color_disEnable : null), // 选中状态的图标
      );
    });
  }

  bool lock(int index) {
    return globalModel.enable == false && (index == 1 || index == 3);
  }

  ///导航栏四个按钮的响应方法
  Future<void> showNaviDialog(String img) async {
    ///搜索
    if (img == assets.settings) {
      SearchView search = SearchView();
      search.show(context);
    }

    ///保存
    else if (img == assets.save) {
      SaveView save = SaveView();
      save.show(context);
    }

    ///导出
    else if (img == assets.upload) {
      UploadView upload = UploadView();
      upload.show(context);
      upload.onOk = () {
        _upload_list = [];
        globalState.state = NotifyData(key: 'DEVICEDATA', body: null);
        EasyLoading.show(status: 'waiting...', dismissOnTap: false);
      };

      ///分享upload的log
      // Future.delayed(const Duration(seconds: 10), () {
      //   List<String> list = _upload_list.map(($0) => $0.toHexstr()).toList();

      //   String str = '';
      //   for (var sub in list) {
      //     str += sub + '|';
      //   }
      //   tempshare(str);
      // });
    }

    ///设置密码
    else if (img == assets.password) {
      String password = await loadString('App_key');
      if (password.isEmpty) {
        await saveString('App_key', '123456');
        password = '123456';
      }
      PasswordInput input = PasswordInput(
          title: 'Please enter your password',
          style: PasswordInputStyle.enterOld,
          prefs_key: 'App_key',
          password: password);
      input.show(context);
      input.onOK = (value) {
        globalModel.enable = true;
        realodAllPage();
        setState(() {});
      };
    }
  }

  ///导航栏四个按钮
  Widget _appBarItem(String img, String? tips, BuildContext context) {
    bool isred = img == assets.settings && BluetoothManager.instance.connectedDeviceList.isNotEmpty;

    return IconButton(
      tooltip: tips,
      enableFeedback: true,
      icon: SizedBox(
        width: 25,
        height: 25,
        child: Stack(
          children: [
            Center(child: Image.asset(img, fit: BoxFit.fitHeight, width: 25)),
            Center(
                child: Container(
              width: 8,
              height: 8,
              decoration: BoxDecoration(
                color: isred ? Colors.red : Colors.transparent,
                borderRadius: BorderRadius.circular(isred ? 4.0 : 0),
              ),
            )),
          ],
        ),
      ),
      onPressed: () => showNaviDialog(img),
    );
  }

  ///刷新所有页面
  void realodAllPage() {
    for (var page in _pages) {
      page.kstate.realod();
    }
  }

  @override
  Widget build(BuildContext context) {
    ///键盘全局键盘是否是弹出状态，
    return KeyboardVisibilityBuilder(builder: (context, showKey) {
      return GestureDetector(
        onTap: () {
          ///如果编辑状态结束，全局固定选中的通道，一些需要输入的数值的范围
          for (var ch in globalModel.select_ch_list) {
            //handle_delay(ch);
            ch.high_pass!.freq = max(ch.high_pass!.freq, ch.high_pass!.min_freq);
            ch.high_pass!.freq = min(ch.high_pass!.freq, ch.high_pass!.max_freq);
            ch.low_pass!.freq = max(ch.low_pass!.freq, ch.low_pass!.min_freq);
            ch.low_pass!.freq = min(ch.low_pass!.freq, ch.low_pass!.max_freq);
          }
          FocusScope.of(context).unfocus(); // 取消焦点，隐藏键盘
          if (showKey) {
            realodAllPage();
          }
        },

        ///如果是弹出状态，，AbsorbPointer就吸收所有子组件的点击事件
        child: AbsorbPointer(
          absorbing: showKey,
          child: Scaffold(
            ///将 Scaffold 的 body 部分扩展到 AppBar 背后
            //extendBodyBehindAppBar: true,
            // resizeToAvoidBottomInset: false, // 禁止页面整体上移

            ///设置appbar背景
            appBar: PreferredSize(
                preferredSize: const Size.fromHeight(40),
                child: Stack(fit: StackFit.expand, children: [
                  Image.asset(assets.bg_nav, fit: BoxFit.cover),
                  AppBar(
                    backgroundColor: Colors.transparent,
                    title: null,
                    centerTitle: true,
                    flexibleSpace: Padding(
                      padding: const EdgeInsets.only(left: 5, top: 20, right: 5),
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          RawGestureDetector(
                            gestures: {
                              LongPressGestureRecognizer:
                                  GestureRecognizerFactoryWithHandlers<LongPressGestureRecognizer>(
                                () => _longPressRecognizer,
                                (LongPressGestureRecognizer instance) {
                                  print('object');
                                },
                              )
                            },
                            child: _appBarItem(assets.settings, null, context),
                          ),
                          _appBarItem(assets.save, 'Tuning  presets', context),
                          Expanded(
                            flex: 7,
                            child: Text(
                              _titles[_currentIndex],
                              textAlign: TextAlign.center,
                              style: const TextStyle(fontSize: 20, color: Colors.black, fontWeight: FontWeight.bold),
                            ),
                          ),
                          _appBarItem(assets.upload, 'Upload DSP', context),
                          _appBarItem(assets.password, 'Input password', context),
                        ],
                      ),
                    ),
                  ),
                ])),

            ///主体页面
            body: IndexedStack(
              index: _currentIndex,
              children: _pages,
            ),

            ///设置带有背景图的底部导航栏，BottomNavigationBarThemeData的背景颜色，要透明才能有效果
            bottomNavigationBar: SafeArea(
              child: Container(
                height: 60,
                decoration:
                    const BoxDecoration(image: DecorationImage(image: AssetImage(assets.bg_nav), fit: BoxFit.fill)),
                child: BottomNavigationBar(
                  currentIndex: _currentIndex,
                  onTap: (index) {
                    if (lock(index)) {
                      return;
                    }
                    setState(() {
                      globalState.state = NotifyData(key: '隐藏下拉框');
                      _currentIndex = index;
                      _pages[index].kstate.realod();
                    });
                  },
                  type: BottomNavigationBarType.fixed,
                  showSelectedLabels: false,
                  showUnselectedLabels: false,
                  selectedItemColor: Colors.white,
                  unselectedItemColor: Colors.black,
                  items: _tabItems,
                ),
              ),
            ),

            endDrawer: isDebugLog ? const LogView() : null,
          ),
        ),
      );
    });
  }
}

extension _MyHomeControllerStateExtesion2 on _MyHomeControllerState {
  ///被动监听应用外的文件
  void listenFile() {
    FileReceiver.listen((hex) {
      _handleFile(hex);
    });
  }

  ///主动读取应用外的文件
  Future<void> readFile() async {
    final fileReceiver = FileReceiver();
    final hex = await fileReceiver.readFile();
    _handleFile(hex);
  }

  void _handleFile(String? hex) {
    if (hex != null && hex.isNotEmpty) {
      EasyLoading.show(status: 'waiting...', dismissOnTap: false);

      ///1，拿到分享的数据，先转换成本地模型
      List<String> list = hex.split('|');
      List<List<int>> bytes = list.map(($0) => $0.bytes).toList();
      globalModel.dataToModel(bytes);

      ///2，再同步到设备
      globalModel.data = hex;
      globalModel.sendToDevice(tag: 'UPDATE');
    }
  }
}

///蓝牙的一些监听
extension _MyHomeControllerStateExtesion on _MyHomeControllerState {
  void listenBluetooth(BuildContext context) {
    ///监听蓝牙外设连接状态
    _conncetSubscription ??= BluetoothManager.instance.connectionStateStream.listen((p0) {
      var state = p0.values.first;
      switch (state) {
        case BluetoothConnectionState.connected:
          EasyLoading.showSuccess('Connect successfully');
          setState(() {});

          ///提示隐藏后，再弹出上传数据
          Future.delayed(const Duration(milliseconds: 1500), () {
            EasyLoading.dismiss();
            showNaviDialog(assets.upload);
          });

        case BluetoothConnectionState.disconnected:
          EasyLoading.showInfo('Disconnected!', duration: const Duration(milliseconds: 1500));
          setState(() {});
        case BluetoothConnectionState.connecting:
          break;
        case BluetoothConnectionState.disconnecting:
          print('设备断开连接中');
          break;
      }
    });

    ///监听蓝牙广播状态
    _responsesSubscription ??= BluetoothManager.instance.bluetoothStateStream.listen((state) {
      switch (state) {
        case BluetoothAdapterState.on:
          break;
        case BluetoothAdapterState.off:
          EasyLoading.showInfo('Bluetooth turned off');
          break;
        default:
      }
    }, onError: (error) {
      EasyLoading.showInfo('${error.message}');
    });

    ///监听数据回调
    BluetoothManager.instance.responseStream.listen((value) {
      var bytes = value.values.first.values.first;
      print('收到蓝牙上传的数据是 == ${bytes.toHexstr(' |')}‘');

      if (isDebugLog) {
        ///日志
        var text = '接受：${bytes.toHexstr('|')}';
        LogNotifier.addLog(navigatorKey.currentContext, text);
      }

      ///从设备upload 到本地
      if (value.values.first.values.first.length == 20) {
        if (_upload_list.isEmpty) {
          EasyLoading.show(status: 'uploading...', dismissOnTap: false);
        }
        if (_upload_list.length < 308) {
          _upload_list.add(bytes);
        }

        ///兼容客户公板返回的是307条数据，
        if (_upload_list.length == 307) {
          ///兼容客户公板返回的是307条条数据，主动延迟
          Future.delayed(const Duration(seconds: 1), () {
            ///所有数据upload后，转换成本地数据
            globalModel.dataToModel(_upload_list);

            ///分享upload的log
            // List<String> list =
            //     _upload_list.map(($0) => $0.toHexstr()).toList();

            // String str = '';
            // for (var sub in list) {
            //   str += sub + '|';
            // }
            // tempshare(str);
            _upload_list = [];
          });

          ///延迟1秒，通知UI更新
          Future.delayed(const Duration(seconds: 1), () {
            globalState.state = NotifyData(key: '全部刷新');
            EasyLoading.showSuccess('Upload Successfully');
          });
          return;
        }
      }
    });
  }
}
